package com.mmy.fta.trade.server.websocket;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author qiang.lin
 * @since 2021/11/5
 */

@Slf4j
@ServerEndpoint(value = "/order/webSocket/{openId}")
// ws://10.190.66.14:8083/order/webSocket/{openId}
@Component
public class ShipperWebSocketTest {

        //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
        private static int onlineCount = 0;
        //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
        private static CopyOnWriteArraySet<ShipperWebSocketTest> webSocketSet = new CopyOnWriteArraySet();
        //与某个客户端的连接会话，需要通过它来给客户端发送数据
        private Session session;
        private String openId;

        @OnOpen
        public void onOPen(@PathParam("openId") String openId, Session session) {
            this.openId = openId;
            this.session = session;
            //加入set中
            webSocketSet.add(this);
            //在线数加1
            addOnlineCount();
            try {
                sendMessage("{\"msg\":\"success\"}");
            } catch (IOException e) {
                log.info("webSocket-OnOpen-error:{}",e);
            }
        }


        @OnMessage
        public void onMessage(String message, Session session) throws EncodeException, IOException {
            log.info("用户登录！"+message);
            log.info("当前在线人数！"+ onlineCount);
        }

        @OnClose
        public void onClose() {
            webSocketSet.remove(this);  //从set中删除
            subOnlineCount();           //在线数减1
            log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
        }

        @OnError
        public void onErroe(Session session, Throwable error) {
            log.info("发生错误");
            error.printStackTrace();
        }
        public  void sendMessage(String message) throws IOException {

            this.session.getBasicRemote().sendText(message);

        }
        /**
         * 群发自定义消息
         * */
        public  void sendInfo(String message) throws IOException {
            for (ShipperWebSocketTest item : webSocketSet) {
                item.sendMessage(message);
            }
        }

        /**
         * 定向自定义消息
         * */
        public void sendSomeoneInfo(String message,String someone) throws IOException {
            for (ShipperWebSocketTest item : webSocketSet) {
                try {
                    if(item.openId.equals(someone)) {
                        item.sendMessage(message);
                        log.info("开始推送信息到："+someone);
                    }
                } catch (IOException e) {
                    continue;
                }
            }
        }

        public static synchronized int getOnlineCount() {
            return onlineCount;
        }

        public static synchronized void addOnlineCount() {
            ShipperWebSocketTest.onlineCount++;
        }

        public static synchronized void subOnlineCount() {
            ShipperWebSocketTest.onlineCount--;
        }

}

